package com.evolve.autotest.actions;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import com.evolve.autotest.ReturnValue;
import com.evolve.autotest.util.FileUtil;

public class ScriptAction extends Action {

	private final File scriptFile;
	private String name;
	
	public ScriptAction(final File actionFile) {
		scriptFile = actionFile;
		
		name = FileUtil.extractSimpleName(actionFile);
	}

	/**
	 * Gets the name of the action
	 */
	public String getName() {
		return name;
	}
	
	public ReturnValue execute() {
		
		if (!scriptFile.canRead()) {
			addTrouble("Script " + scriptFile.getName() + " is not readable");
			return ReturnValue.ERROR;
		}
		
		try {
			Process process = Runtime.getRuntime().exec(scriptFile.getAbsolutePath());
			
			String processOutput = readOutput(process);
			
			int exitValue = process.exitValue();
			
			if (exitValue != 0) {
				addTrouble("Script " + scriptFile.getName() + " exited with code " + exitValue);
				addTrouble(processOutput);
				return ReturnValue.FAILED;
			} 
		} catch (IOException e) {
			addTrouble("Script " + scriptFile.getName() + " was unable to execute ");
			return ReturnValue.ERROR;
		}
		
		return ReturnValue.OK;
	}

	private String readOutput(Process process) {
		InputStream in = process.getInputStream();

        int c;
        
        StringBuffer buffer = new StringBuffer();
        
        try {
			while ((c = in.read()) != -1) {
			    buffer.append((char)c);
			}
		} catch (IOException e) {
			return "";
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				return "";
			}
		}
		
		return buffer.toString();
	}
}
